double value ; int tenths = 0; int inc = 1; // each "1" represents one tenth while ( tenths <= 100 ) // 100 tenths is 10.0 { value = tenths/10.0 ; // be sure to divide by a double 10.0 System.out.println( "value:" + value ); tenths = tenths + inc ; } System.out.println( "done");
You might want a
double
or float
for the loop control variable.
You would add 0.1 to it each iteration.
This would nearly work,
but leads to errors.
The value 0.1 cannot be accurately represented in binary.
A loop that repeatedly adds 0.1
to a variable will accumulate errors.
Just for fun, here is a program fragment that does just that. Enter various limit amounts and see how much error there is:
// the user (you) enters a value for limit float inc = 0.1 ; float value = 0.0 ; while ( value < limit ) { value = value + inc; } System.out.println( "Value was " + value + " when the loop ended");